package fr.umlv.m2.jee.spij.persistence.education.dao;

import fr.umlv.m2.jee.spij.framework.dao.hibernate.AbstractHibernateDAO;
import fr.umlv.m2.jee.spij.persistence.education.IProjectDAO;
import fr.umlv.m2.jee.spij.persistence.education.Project;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 *
 */
@Repository("hibernateProjectDAO")
public class HibernateProjectDAO extends AbstractHibernateDAO<Long, Project>
        implements IProjectDAO {

    @Override
    public final Project findBySubject(final String subject) {
        Session session = getHibernateSession();
        Criteria criteria = session.createCriteria(Project.class);
        criteria.add(Restrictions.eq("subject", subject));
        return (Project) criteria.uniqueResult();
    }

    @Override
    public final List<Project> findByLdapActorAndUnitId(
            final long unitId,
            final String ldapActor,
            final String type) {

        if (type.equals("Student")) {
            Session session = getHibernateSession();
            Criteria criteria = session.createCriteria(Project.class);
            criteria.createCriteria("students")
                    .add(Restrictions.eq("studentLogin", ldapActor));
            criteria.add(Restrictions.eq("unit", unitId));
            return criteria.list();
        } else if (type.equals("Teacher")) {
            Session session = getHibernateSession();
            Criteria criteria = session.createCriteria(Project.class);
            criteria.createCriteria("teachers")
                    .add(Restrictions.eq("teacherLogin", ldapActor));
            criteria.add(Restrictions.eq("unit", unitId));
            return criteria.list();
        }
        return null;
    }


    @Override
    public final List<Project> findByLdapActor(
            final String ldapActor,
            final String type) {
        if (type.equals("Student")) {
            Session session = getHibernateSession();
            Criteria criteria = session.createCriteria(Project.class);
            criteria.createCriteria("students")
                    .add(Restrictions.eq("studentLogin", ldapActor));
            return criteria.list();
        } else if (type.equals("Teacher")) {
            Session session = getHibernateSession();
            Criteria criteria = session.createCriteria(Project.class);
            criteria.createCriteria("teachers")
                    .add(Restrictions.eq("teacherLogin", ldapActor));
            return criteria.list();
        }
        return null;
    }
}
